package osmparser;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
 * 
 * @author zuq
 */
public class RelationParser {

	public static boolean isRelation(Node node) {
		return node.getNodeName().equals("relation");
	}

	public static OSMRelation parseRelation(Node node,
			Map<String, OSMNode> nodesMap, Map<String, OSMWay> waysMap) {
		NamedNodeMap atts = node.getAttributes();
		String id = atts.getNamedItem("id").getNodeValue();
		List<AbstractNode> members = new ArrayList<AbstractNode>();

		NodeList childNodes = node.getChildNodes();

		for (int i = 0; i < childNodes.getLength(); i++) {
			node = childNodes.item(i);
			NamedNodeMap map = node.getAttributes();
			if (node.getNodeName().equals("member")) {
				if (map.getNamedItem("type").getNodeValue().equals("node"))
					members.add(nodesMap.get(map.getNamedItem("ref")
							.getNodeValue()));
				else if (map.getNamedItem("type").getNodeValue().equals("way"))
					members.add(waysMap.get(map.getNamedItem("ref")
							.getNodeValue()));
			}
		}

		return new OSMRelation(id, getAttribute(atts, "visible"), getAttribute(
				atts, "timestamp"), getAttribute(atts, "version"),
				getAttribute(atts, "changeset"), getAttribute(atts, "user"),
				getAttribute(atts, "uid"), members, OSMParser.parseTags(node
						.getChildNodes()));
	}

	// Private Methods ---------------------------------------------------------

	private static String getAttribute(NamedNodeMap atts, String key) {
		Node node = atts.getNamedItem(key);
		return (node == null) ? null : node.getNodeValue();
	}

}
